package com.xiaoxiong.gobang.ai;

import android.util.Log;

import com.xiaoxiong.gobang.bean.GameState;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author xiaoxiong
 * @Package com.xiaoxiong.gobang.ai
 * @Description:第二个AI
 * @email 249900679@qq.com
 * @date 2016/4/4 17:00
 */
public class SecondAi implements Searcher {

    private GameState gameState;
    private int depth;
    private int pos;
    private List<Integer> chessDis;

    @Override
    public int SearchBestPlay(GameState state, int depth) {
        this.gameState = state;
        this.depth = depth;
        pos = 0;
        chessDis = new ArrayList<>();
        SecondAiSearcher(depth, false);

        int len = chessDis.size();
        if (len > 0) {
            Random random = new Random();
            int dis = random.nextInt(len);
            pos = chessDis.get(dis);
            chessDis.clear();
        }
        if (pos == 0) {
            Random random = new Random();
            int dis = random.nextInt(256);
            while (!gameState.checkDis(dis)) {
                dis = random.nextInt(256);
            }
            pos = dis;
        }
        Log.d("pos",pos + "");
        return pos;
    }

    /**
     * 查找落子点
     * 最大最小值搜索
     *
     * @return
     */
    private int SecondAiSearcher(int cur, boolean isMe) {
        if (cur == 0) {
            return gameState.Evaluate(0, depth);
        }
        int score = isMe ? -999999999 : 999999999;
        for (int i = 17; i <= 255; ++i) {
            if (gameState.checkDis(i)) {
                //我方在该位置下棋
                if (gameState.PutChess(i, isMe)) {
                    gameState.BackChess(i, isMe);
                    pos = i;
                    chessDis.clear();
                    return 999999999;
                }
                int value = SecondAiSearcher(cur - 1, !isMe);
                gameState.BackChess(i, isMe);
                if (score == value) {
                    chessDis.add(i);
                } else {
                    if (isMe) {
                        if (score < value) {
                            chessDis.clear();
                            chessDis.add(i);
                            score = value;
                        }
                    } else {
                        if (score > value) {
                            chessDis.clear();
                            chessDis.add(i);
                            score = value;
                        }
                    }
                }
            }
        }
        return score;
    }
}
